package com.inool.custom.interceptor;

import com.inool.common.login.LoginUser;
import com.inool.common.login.LoginUserHolder;
import com.inool.common.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parsePayload(token);
        String userId = claims.get("userId", String.class);
        String role = claims.get("role", String.class);        
        LoginUserHolder.setLoginUser(new LoginUser(userId, role));
        
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
